package com.ysstech.system.service.impl;

import java.io.File;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ysstech.common.cache.RedisCacheManager;
import com.ysstech.common.entity.TreeNode;
import com.ysstech.common.entity.Organization;
import com.ysstech.common.exception.BusinessException;
import com.ysstech.common.util.fileutil.FileUtil;
import com.ysstech.system.enums.SystemEnum;
import com.ysstech.system.mapper.OrganizationMapper;
import com.ysstech.system.service.OrganizationService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 * 机构服务实现类
 * </p>
 *
 * @author lishuangliang
 * @since 2020-09-12
 */
@Service
@Slf4j
public class OrganizationServiceImpl extends ServiceImpl<OrganizationMapper, Organization> implements OrganizationService {
    @Autowired
    private RedisCacheManager redisCacheManager;

    /**
     * 查询机构树信息
     *
     * @return
     */
    public List<TreeNode> queryOrganizationTree(String orgId) throws Exception {
        if (StringUtils.isBlank(orgId)) {
            throw new BusinessException("获取机构信息失败，请稍后重试！");
        }
        List<TreeNode> list = new ArrayList<>();
        List<Organization> listOrganization = this.list();
        if (CollectionUtils.isEmpty(listOrganization)) {
            return list;
        }
        /*Organization organization = this.getById(orgId);
        TreeNode treeNode = organizationToNode(organization);
        treeNode.setState("open");
        treeNode.setChildren(this.recursionTree(Organization.getId(), listOrganization));
        list.add(treeNode);*/
        list.addAll(this.recursionTree("0", listOrganization));
        return list;
    }

    private List<TreeNode> recursionTree(String orgId, List<Organization> listOrganization) throws Exception {
        List<TreeNode> list = new ArrayList<>();
        for (Organization organization : listOrganization) {
            if (!orgId.equals(organization.getParentId())) {
                continue;
            }
            TreeNode treeNode = this.organizationToNode(organization);
            List<TreeNode> children = recursionTree(organization.getId(), listOrganization);
            if (null == children || children.size() == 0) {
                treeNode.setState("open");
            } else {
                treeNode.setChildren(children);
            }
            list.add(treeNode);
        }
        return list;
    }

    /**
     * 将业务功能转化成TreeNode
     */
    private TreeNode organizationToNode(Organization organization) {
        TreeNode node = new TreeNode();
        node.setId(organization.getId());
        node.setText(organization.getFullName());
        node.setState("closed");
        node.setChecked(false);
        node.setIconCls("icon-bricks");
        node.setPId(organization.getParentId());
        return node;
    }

    /**
     * 读取机构文件
     *
     * @param file
     * @throws Exception
     */
    public void readExcel(MultipartFile file) throws Exception {
        File newfile = null;
        try {
            if (null == file) {
                throw new BusinessException("获取文件数据失败，请稍后重试！");
            }
            newfile = FileUtil.MultipartFileToFile(file);
            if (null == newfile) {
                throw new BusinessException("获取文件数据失败，请稍后重试！");
            }
            List<List<Object>> list = FileUtil.readerExcelListObject(newfile);
            List<Organization> organizationList = new ArrayList<>();
            for (int i = 1; i < list.size(); i++) {
                List<Object> objectList = list.get(i);
                if (null == objectList || objectList.size() != 10) {
                    continue;
                }
                Organization organization = new Organization();
                organization.setId(String.valueOf(objectList.get(0)));
                organization.setParentId(String.valueOf(objectList.get(1)));
                organization.setFullName(String.valueOf(objectList.get(2)));
                organization.setShorterName(String.valueOf(objectList.get(3)));
                organization.setDescription(String.valueOf(objectList.get(4)));
                organization.setType(Integer.valueOf(String.valueOf(objectList.get(5))));
                organization.setStatus(Integer.valueOf(String.valueOf(objectList.get(6))));
                organization.setAddress(String.valueOf(objectList.get(7)));
                organization.setTelephoneNumber(String.valueOf(objectList.get(8)));
                organization.setAddTime(LocalDateTime.now());
                organizationList.add(organization);
            }
            if (organizationList.size() == 0) {
                throw new BusinessException("获取文件数据为空，请稍后重试！");
            }
            this.saveOrUpdateBatch(organizationList);
        } catch (BusinessException ex) {
            throw new BusinessException(ex.getMessage());
        } finally {
            FileUtil.delteTempFile(newfile);
        }
    }


    /**
     * 查询所有下级机构的机构集合
     *
     * @param orgId 机构编号
     * @return
     * @throws Exception
     */
    public List<Organization> queryListOrganization(String orgId) throws Exception {
        if (StringUtils.isBlank(orgId)) {
            throw new BusinessException("获取机构信息失败，请稍后重试！");
        }
        List<String> list = this.queryOrganizationIds(orgId);
        QueryWrapper<Organization> wrapper = new QueryWrapper<>();
        wrapper.in("ID", list);
        List<Organization> listOrganization = this.list(wrapper);
        return listOrganization;
    }

    /**
     * 查询所有下级机构的机构id集合
     *
     * @param orgId
     * @return
     * @throws Exception
     */
    public List<String> queryOrganizationIds(String orgId) throws Exception {
        if (StringUtils.isBlank(orgId)) {
            throw new BusinessException("获取机构信息失败，请稍后重试！");
        }
        List<String> strList = new ArrayList<>();
        strList.add(orgId);
        List<Organization> list = this.list();
        recursionIds(orgId, strList, list);
        return strList;
    }

    private void recursionIds(String orgId, List<String> strList, List<Organization> list) {
        for (Organization organization : list) {
            if (!orgId.equals(organization.getParentId())) {
                continue;
            }
            strList.add(organization.getId());
            recursionIds(organization.getId(), strList, list);
        }
    }

    /**
     * 缓存里获取机构信息
     *
     * @return
     * @throws Exception
     */
    public Map<String, Organization> getCacheOrganizationMap() throws Exception {
        Map<String, Organization> mapOrganization = new HashMap<>();
        List<Organization> listOrganization = list();
        if (CollectionUtils.isEmpty(listOrganization)) {
            return null;
        }
        for (Organization organization : listOrganization) {
            if (null == organization || StringUtils.isBlank(organization.getId())) {
                continue;
            }
            mapOrganization.put(organization.getId(), organization);
        }
        return mapOrganization;
    }

}
